import axios from 'axios'

export default function ajx(url = '',params = {}, type = 'GET'){
    let promise

    return new Promise((resolve,reject)=>{
        //判断请求
        if('GET' === type.toUpperCase()){
            //拼接字符串
            let paramsStr = ''
            Object.keys(params).forEach(key=>{
                paramsStr += key + '=' +params[key] + '&'
            })
            //过滤最后一个 '&
            if(paramsStr !==''){
                paramsStr = paramsStr.substr(0,paramsStr.lastIndexOf('&'))
            }
            //拼接完整的路径
            url += '?' + paramsStr
            //发起get请求
            promise = axios.get(url)

        }else if('POST' === type.toUpperCase()){
            promise = axios.post(url,params)
        }

        //返回结果
        promise.then((response)=>{
            resolve(response.data)
        }).catch((error)=>{
            reject(error)
        })
    })

}